package com.hmtech.aup.presentation.aiedit

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.hmtech.aup.R
import com.hmtech.aup.util.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import kotlinx.coroutines.launch

/**
 * 自定义底部弹出式图片选择器
 * 特点：
 * 1. 基于BottomSheet实现，可拖拽调整高度
 * 2. 最小高度为屏幕的一半，最大高度为ActionBar以下的全部内容区域
 * 3. 选中图片后不关闭选择器，而是直接跳转到下一个Activity
 */
class BottomSheetImageSelector : AppCompatActivity() {

    private lateinit var bottomSheetBehavior: BottomSheetBehavior<FrameLayout>
    private lateinit var bottomSheetContainer: FrameLayout
    private var screenHeight = 0
    private var actionBarHeight = 0
    
    companion object {
        const val REQUEST_CODE_SELECT_IMAGE = 100
        const val EXTRA_SELECTED_IMAGE = "extra_selected_image"
        
        /**
         * 启动图片选择器
         * @param activity 来源Activity
         * @param requestCode 请求码
         */
        fun start(activity: Activity, requestCode: Int = REQUEST_CODE_SELECT_IMAGE) {
            val intent = Intent(activity, BottomSheetImageSelector::class.java)
            activity.startActivityForResult(intent, requestCode)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bottom_sheet_image_selector)
        
        // 获取屏幕高度和ActionBar高度
        screenHeight = resources.displayMetrics.heightPixels
        val typedValue = android.util.TypedValue()
        if (theme.resolveAttribute(android.R.attr.actionBarSize, typedValue, true)) {
            actionBarHeight = android.util.TypedValue.complexToDimensionPixelSize(
                typedValue.data, resources.displayMetrics
            )
        }
        
        setupBottomSheet()
        initPictureSelector()
    }
    
    private fun setupBottomSheet() {
        bottomSheetContainer = findViewById(R.id.bottom_sheet_container)
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetContainer)
        
        // 设置初始状态为半展开
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
        
        // 设置最小高度为屏幕的一半
        val halfScreenHeight = screenHeight / 2
        bottomSheetBehavior.peekHeight = halfScreenHeight
        
        // 设置最大高度为ActionBar以下的内容区域
        val contentMaxHeight = screenHeight - actionBarHeight
        val layoutParams = bottomSheetContainer.layoutParams as CoordinatorLayout.LayoutParams
        layoutParams.height = contentMaxHeight
        bottomSheetContainer.layoutParams = layoutParams
        
        // 设置回调监听拖拽状态
        bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                // 状态变化时的处理
            }
            
            override fun onSlide(bottomSheet: View, slideOffset: Float) {
                // 滑动过程中的处理
            }
        })
    }
    
    private fun initPictureSelector() {
        lifecycleScope.launch {
            // 在BottomSheet容器中加载PictureSelector
            val fragmentManager = supportFragmentManager
            
            // 使用PictureSelector的Fragment模式
            PictureSelector.create(this@BottomSheetImageSelector)
                .openGallery(SelectMimeType.ofImage()) // 只选择图片
                .setImageEngine(GlideEngine.createGlideEngine()) // 设置图片加载引擎
                .setMaxSelectNum(1) // 最大选择数量
                .isDirectReturnSingle(false) // 不直接返回
                .isPreviewImage(true) // 支持预览
                .isDisplayCamera(true) // 显示相机按钮
                .isGif(false) // 不支持GIF
                .isWebp(false) // 不支持Webp
                .setSelectionMode(SelectModeConfig.SINGLE) // 单选模式
                .isOriginalControl(false) // 不显示原图控制按钮
                .isDisplayTimeAxis(true) // 显示时间轴
                .isPreviewFullScreenMode(true) // 全屏预览
                .setLanguage(-1) // 使用系统语言
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>) {
                        if (result.isNotEmpty()) {
                            // 选中图片后直接跳转到下一个Activity，而不是关闭选择器
                            val selectedMedia = result[0]
                            navigateToNextActivity(selectedMedia)
                        }
                    }
                    
                    override fun onCancel() {
                        // 用户取消选择
                    }
                })
        }
    }
    
    /**
     * 选中图片后跳转到下一个Activity
     */
    private fun navigateToNextActivity(media: LocalMedia) {
        val intent = Intent(this, GhibliStyleActivity::class.java)
        intent.putExtra(EXTRA_SELECTED_IMAGE, media.path)
        startActivity(intent)
        // 注意这里不调用finish()，保持当前Activity不关闭
    }
}
